﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using YookingDBNormal.Class;
using YookingFileIO.Class;
using YookingKitBox.Class.Public;
using YookingSvrDBCall.Class.DBLogic;
using YookingSvrDBCall.Class.DBPub;

namespace YookingBizWQW.Class.Credit.pub
{
    public class clsMbrReward
    {
        //注释：王庆文 2020年04月17日==========================================================================
        //会员第一次绑卡成功之后，需要给自己的上级会员进行绑卡奖励，
        //上级会员的级别不同，奖励的金额也各不相同。绑卡奖励只能一人一次。
        public void CommitBindCardRewardData(string strUnitCode, string strMID)
        {
            DataSet dsMbr = GetMemberInfo(strUnitCode, strMID); //得到当前会员信息
            if (dsMbr != null && dsMbr.Tables.Count > 0 && dsMbr.Tables[0].Rows.Count > 0)
            {
                string strPID = dsMbr.Tables[0].Rows[0]["PID"].ToString(); //上级会员ID
                if (!CheckBindRewardIsExist(strUnitCode, strPID, strMID))  //会员绑卡只能给上级奖励一次
                {
                    DataSet dsALevel = GetMemberInfo(strUnitCode, strPID); //得到上级会员信息
                    if (dsALevel != null && dsALevel.Tables.Count > 0 && dsALevel.Tables[0].Rows.Count > 0)
                    {
                        //上级会员处于哪种级别
                        string strMemberLevel = dsALevel.Tables[0].Rows[0]["MEMBERLEVEL"].ToString();

                        DataSet dsFee = GetMemberUpdReward(strUnitCode, strMemberLevel);
                        if (dsFee != null && dsFee.Tables.Count > 0 && dsFee.Tables[0].Rows.Count > 0)
                        {
                            //指定级别的会员可以得到多少钱的绑卡奖励金
                            string strBindFee = dsFee.Tables[0].Rows[0]["BINDFEE"].ToString();
                       
                            Random rd = new Random(); //随机数实例
                            int iRandom = rd.Next(1000, 9999); //生成四位随机数
                            string strCurValue = DateTime.Now.ToString("yyyyMMddHHmmss");
                            string strOrderID = "HYBK" + strCurValue + iRandom; //订单号

                            //佣金类型：01=一级代理分佣、02=二级代理分佣，03=平台收益
                            //佣金来源：POS01=信用卡刷卡、POS02=信用卡还款、ATM01=信用卡套刷、
                            //          ATM02 =信用卡套入、HBEI01=花呗消费、HBEI02=花呗还款、
                            //          BKGE01 =佣金提现、HYCZ01=会员充值、HYSJ00=会员注册奖励、
                            //          HYSJ01 =升为中级会员奖励、HYSJ02=升为高级会员奖励、
                            //          HYSJ03 =升为顶级会员奖励、HYBK00=普通会员绑卡奖励、
                            //          HYBK01 =中级会员绑卡奖励、HYBK02=高级会员绑卡奖励、HYBK03=顶级会员绑卡奖励
                            string strBkgeFrom = "HYBK" + strMemberLevel;
                            saveIncomeToDB(strUnitCode, strPID, strMID, "01", strBkgeFrom, //一级代理绑卡奖励
                               strOrderID, Convert.ToDouble(strBindFee), strBindFee, strBindFee, 1, "XYK_BankCard");

                            saveIncomeToDB(strUnitCode, strUnitCode, strMID, "03", strBkgeFrom, //平台收入减少
                               strOrderID, -Convert.ToDouble(strBindFee), strBindFee, strBindFee, -1, "XYK_BankCard");
                        }
                    }
                }
            }
        }

        //注释：王庆文 2020年04月17日=====================================================================================
        //会员通过充值、或者发展绑卡下线的方式升级到一定级别时，给自己的上级推荐人一定的升级奖励，
        //奖励金额根据上级会员的级别不同而有所区别。
        //00=用户注册升级，01=直接充值升级，02=充值补差价升级，03=绑卡达到规定人数升级，04=平台管理员操作升级
        public void CommitMbrUpdateRewardData_A(string strUnitCode, string strMID, string strMLevel, string strMbrUpdWay)
        {
            if (strMbrUpdWay != "04") //管理员后台操作升级不需要给奖励
            {
                DataSet dsMbr = GetMemberInfo(strUnitCode, strMID); //得到当前会员信息
                if (dsMbr != null && dsMbr.Tables.Count > 0 && dsMbr.Tables[0].Rows.Count > 0)
                {
                    string strPID = dsMbr.Tables[0].Rows[0]["PID"].ToString(); //上级会员ID

                    DataSet dsALevel = GetMemberInfo(strUnitCode, strPID); //得到上级会员信息
                    if (dsALevel != null && dsALevel.Tables.Count > 0 && dsALevel.Tables[0].Rows.Count > 0)
                    {
                        //上级会员处于哪种级别
                        string strPLevel = dsALevel.Tables[0].Rows[0]["MEMBERLEVEL"].ToString();

                        DataSet dsFee = GetMemberUpdReward(strUnitCode, strPLevel);
                        if (dsFee != null && dsFee.Tables.Count > 0 && dsFee.Tables[0].Rows.Count > 0)
                        {
                            //指定级别的父会员可以得到多少钱的下级会员升级奖励金
                            string strUpdFee = dsFee.Tables[0].Rows[0]["A" + strMLevel + "FEE"].ToString();
                            double dUpdFee = Convert.ToDouble(strUpdFee); //转成可运算的数字类型

                            //同一个会员升级到不同级别的时候，
                            //上级推荐人的升级奖励需要扣除之前已经奖励过的金额
                            double dFeeSum = GetUpdRewardAmountSum(strUnitCode, strPID, strMID, "01");
                            if (dFeeSum < dUpdFee) //升级奖励没有到达最高上限额度
                            {
                                //扣除之前的奖励之外，本次实际的奖励金额
                                double dPayFee = dUpdFee - dFeeSum; 
                                string strPayFee = dPayFee.ToString();

                                Random rd = new Random(); //随机数实例
                                int iRandom = rd.Next(1000, 9999); //生成四位随机数
                                string strCurValue = DateTime.Now.ToString("yyyyMMddHHmmss");
                                string strOrderID = "HYSJ" + strCurValue + iRandom; //订单号

                                //佣金类型：01=一级代理分佣、02=二级代理分佣，03=平台收益
                                //佣金来源：POS01=信用卡刷卡、POS02=信用卡还款、ATM01=信用卡套刷、
                                //          ATM02 =信用卡套入、HBEI01=花呗消费、HBEI02=花呗还款、
                                //          BKGE01 =佣金提现、HYCZ01=会员充值、HYSJ00=会员注册奖励、
                                //          HYSJ01 =升为中级会员奖励、HYSJ02=升为高级会员奖励、
                                //          HYSJ03 =升为顶级会员奖励、HYBK00=普通会员绑卡奖励、
                                //          HYBK01 =中级会员绑卡奖励、HYBK02=高级会员绑卡奖励、HYBK03=顶级会员绑卡奖励
                                string strBkgeFrom = "HYSJ" + strMLevel;
                                saveIncomeToDB(strUnitCode, strPID, strMID, "01", strBkgeFrom, //一级代理升级奖励
                                          strOrderID, dPayFee, strPayFee, strPayFee, 1, "XYK_Member_Info");

                                saveIncomeToDB(strUnitCode, strUnitCode, strMID, "03", strBkgeFrom, //平台收入减少
                                          strOrderID, -dPayFee, strPayFee, strPayFee, -1, "XYK_Member_Info");
                            }
                        }
                    }
                }
            }
        }

        //注释：王庆文 2020年04月17日=====================================================================================
        //会员通过充值、或者发展绑卡下线的方式升级到一定级别时，给自己的上上级推荐人一定的升级奖励，
        //奖励金额根据上上级会员的级别不同而有所区别。
        //00=用户注册升级，01=直接充值升级，02=充值补差价升级，03=绑卡达到规定人数升级，04=平台管理员操作升级
        public void CommitMbrUpdateRewardData_B(string strUnitCode, string strMID, string strMLevel, string strMbrUpdWay)
        {
            if (strMbrUpdWay != "04") //管理员后台操作升级不需要给奖励
            {
                DataSet dsMbr = GetMemberInfo(strUnitCode, strMID); //得到当前会员信息
                if (dsMbr != null && dsMbr.Tables.Count > 0 && dsMbr.Tables[0].Rows.Count > 0)
                {
                    string strGPID = dsMbr.Tables[0].Rows[0]["GPID"].ToString(); //上上级会员ID

                    DataSet dsBLevel = GetMemberInfo(strUnitCode, strGPID); //得到上上级会员信息
                    if (dsBLevel != null && dsBLevel.Tables.Count > 0 && dsBLevel.Tables[0].Rows.Count > 0)
                    {
                        //上上级会员处于哪种级别
                        string strGPLevel = dsBLevel.Tables[0].Rows[0]["MEMBERLEVEL"].ToString();

                        DataSet dsFee = GetMemberUpdReward(strUnitCode, strGPLevel);
                        if (dsFee != null && dsFee.Tables.Count > 0 && dsFee.Tables[0].Rows.Count > 0)
                        {
                            //指定级别的祖父会员可以得到多少钱的下下级会员升级奖励金
                            string strUpdFee = dsFee.Tables[0].Rows[0]["B" + strMLevel + "FEE"].ToString();
                            double dUpdFee = Convert.ToDouble(strUpdFee); //转成可运算的数字类型

                            //同一个会员升级到不同级别的时候，
                            //给上上级推荐人的升级奖励需要扣除之前已经奖励过的金额
                            double dFeeSum = GetUpdRewardAmountSum(strUnitCode, strGPID, strMID, "02");
                            if (dFeeSum < dUpdFee) //升级奖励没有到达最高上限额度
                            {
                                //扣除之前的奖励之外，本次实际的奖励金额
                                double dPayFee = dUpdFee - dFeeSum;
                                string strPayFee = dPayFee.ToString();

                                Random rd = new Random(); //随机数实例
                                int iRandom = rd.Next(1000, 9999); //生成四位随机数
                                string strCurValue = DateTime.Now.ToString("yyyyMMddHHmmss");
                                string strOrderID = "HYSJ" + strCurValue + iRandom; //订单号

                                //佣金类型：01=一级代理分佣、02=二级代理分佣，03=平台收益
                                //佣金来源：POS01=信用卡刷卡、POS02=信用卡还款、ATM01=信用卡套刷、
                                //          ATM02 =信用卡套入、HBEI01=花呗消费、HBEI02=花呗还款、
                                //          BKGE01 =佣金提现、HYCZ01=会员充值、HYSJ00=会员注册奖励、
                                //          HYSJ01 =升为中级会员奖励、HYSJ02=升为高级会员奖励、
                                //          HYSJ03 =升为顶级会员奖励、HYBK00=普通会员绑卡奖励、
                                //          HYBK01 =中级会员绑卡奖励、HYBK02=高级会员绑卡奖励、HYBK03=顶级会员绑卡奖励
                                string strBkgeFrom = "HYSJ" + strMLevel;
                                saveIncomeToDB(strUnitCode, strGPID, strMID, "02", strBkgeFrom, //二级代理升级奖励
                                         strOrderID, dPayFee, strPayFee, strPayFee, 1, "XYK_Member_Info");

                                saveIncomeToDB(strUnitCode, strUnitCode, strMID, "03", strBkgeFrom, //平台收入减少
                                         strOrderID, -dPayFee, strPayFee, strPayFee, -1, "XYK_Member_Info");
                            }
                        }
                    }
                }
            }
        }

        #region 会员绑卡奖励、会员升级奖励用到的公共函数

        //注释：王庆文 2020年04月17日====================================================================
        //查询指定平台服务商中，指定ID的会员基本信息
        public DataSet GetMemberInfo(string strUnitCode, string strMID)
        {
            StringBuilder sbQuerySQL = new StringBuilder();
            sbQuerySQL.AppendLine(" SELECT ");
            sbQuerySQL.AppendLine("     UNITCODE, ");
            sbQuerySQL.AppendLine(" 	GPID, ");
            sbQuerySQL.AppendLine(" 	PID, ");
            sbQuerySQL.AppendLine(" 	MID, ");
            sbQuerySQL.AppendLine(" 	MEMBERLEVEL, ");
            sbQuerySQL.AppendLine(" 	INVITECODE, ");
            sbQuerySQL.AppendLine(" 	ISBINDCARD, ");
            sbQuerySQL.AppendLine(" 	ISREALNAME, ");
            sbQuerySQL.AppendLine(" 	MBRUPDTIME, ");
            sbQuerySQL.AppendLine(" 	MBRUPDWAY, ");
            sbQuerySQL.AppendLine(" 	REALBINDCOUNT, ");
            sbQuerySQL.AppendLine(" 	VIRTBINDCOUNT, ");
            sbQuerySQL.AppendLine(" 	OTHERMEMO ");
            sbQuerySQL.AppendLine(" FROM XYK_MEMBER_INFO T ");
            sbQuerySQL.AppendLine(" WHERE " + clsSQLSyntax.IsNullSQL("Data", "SYS_CANCELDATETIME"));
            sbQuerySQL.AppendLine("   AND UNITCODE = '" + strUnitCode + "' ");
            sbQuerySQL.AppendLine("   AND MID = '" + strMID + "' ");

            //clsRWFile myLog = new clsRWFile(); //将待执行的SQL语句记录下来
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", sbQuerySQL.ToString());

            clsDbSQLLogic myDB = new clsDbSQLLogic(); //实例化数据库操作类
            return myDB.YookingExecuteDataSet("Data", sbQuerySQL.ToString());
        }

        //注释：王庆文 2020年04月13日===================================================
        //查询会员升级奖励方案字典数据
        private DataSet GetMemberUpdReward(string strUnitCode, string strMemberLevel)
        {
            #region 生成查询记录的SQL语句

            StringBuilder sbQuerySQL = new StringBuilder();
            sbQuerySQL.AppendLine(" SELECT ");
            sbQuerySQL.AppendLine("     UNITCODE, ");
            sbQuerySQL.AppendLine("     MEMBERLEVEL, ");
            sbQuerySQL.AppendLine("     BINDFEE, ");
            sbQuerySQL.AppendLine("     A00FEE, ");
            sbQuerySQL.AppendLine("     A01FEE, ");
            sbQuerySQL.AppendLine("     A02FEE, ");
            sbQuerySQL.AppendLine("     A03FEE, ");
            sbQuerySQL.AppendLine("     B00FEE, ");
            sbQuerySQL.AppendLine("     B01FEE, ");
            sbQuerySQL.AppendLine("     B02FEE, ");
            sbQuerySQL.AppendLine("     B03FEE, ");
            sbQuerySQL.AppendLine("     OTHERMEMO ");
            sbQuerySQL.AppendLine(" FROM XYK_MEMBER_UPDREWARD T ");
            sbQuerySQL.AppendLine(" WHERE " + clsSQLSyntax.IsNullSQL("Data", "T.SYS_CANCELDATETIME"));
            sbQuerySQL.AppendLine(" AND T.UNITCODE = '" + strUnitCode + "' ");
            sbQuerySQL.AppendLine(" AND T.MEMBERLEVEL = '" + strMemberLevel + "' ");

            #endregion

            //clsRWFile myLog = new clsRWFile(); //将待执行的SQL语句记录下来
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", sbQuerySQL.ToString());

            clsDbSQLLogic myDB = new clsDbSQLLogic(); //实例化数据库操作类
            return myDB.YookingExecuteDataSet("Data", sbQuerySQL.ToString());
        }

        //注释：王庆文 2020年04月17日=============================================================================
        //判断当前绑卡会员的上级会员是否已经得到过该会员的绑卡奖励，同一会员、同一上级只能奖励一次，不能反复奖励。
        private bool CheckBindRewardIsExist(string strUnitCode,string strReceCode, string strGiveCode)
        {
            StringBuilder sbQuerySQL = new StringBuilder();
            sbQuerySQL.AppendLine(" SELECT COUNT(1) FROM XYK_INCOME_BILL T ");
            sbQuerySQL.AppendLine(" WHERE " + clsSQLSyntax.IsNullSQL("Data", "T.SYS_CANCELDATETIME"));
            sbQuerySQL.AppendLine("   AND T.UNITCODE = '" + strUnitCode + "' ");
            sbQuerySQL.AppendLine("   AND T.RECECODE = '" + strReceCode + "' ");
            sbQuerySQL.AppendLine("   AND T.GIVECODE = '" + strGiveCode + "' ");
            sbQuerySQL.AppendLine("   AND T.ISSUCCESS = '1' ");
            sbQuerySQL.AppendLine("   AND T.BKGETYPE = '01' ");
            sbQuerySQL.AppendLine("   AND T.BKGEFROM LIKE 'HYBK%' ");
            sbQuerySQL.AppendLine("   AND upper(T.DBTBLNAME) = 'XYK_BANKCARD' ");
      
            //clsRWFile myLog = new clsRWFile(); //将待执行的SQL语句记录下来
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", sbQuerySQL.ToString(),false);

            clsDbSQLLogic myDB = new clsDbSQLLogic(); //实例化数据库操作类
            object objCount = myDB.YookingGetDataScalar("Data", sbQuerySQL.ToString());

            if (Convert.ToInt32(objCount) == 0)
            {
                return false; //绑卡奖励记录不存在
            }
            else
            {
                return true; //已经进行过绑卡奖励
            }     
        }

        //注释：王庆文 2020年04月17日===========================================================================================
        //同一个会员升级到不同级别的时候，给上级、上上级推荐人的升级奖励需要扣除之前已经奖励过的金额
        private double GetUpdRewardAmountSum(string strUnitCode, string strReceCode, string strGiveCode, string strBkgeType)
        {
            #region 生成统计奖金总额的SQL语句

            StringBuilder sbQuerySQL = new StringBuilder();
            sbQuerySQL.AppendLine(" SELECT SUM(BKGEAMOUNT) as ALLAMOUNT FROM XYK_INCOME_BILL T ");
            sbQuerySQL.AppendLine(" WHERE " + clsSQLSyntax.IsNullSQL("Data", "T.SYS_CANCELDATETIME"));
            sbQuerySQL.AppendLine("   AND T.UNITCODE = '" + strUnitCode + "' ");
            sbQuerySQL.AppendLine("   AND T.RECECODE = '" + strReceCode + "' ");
            sbQuerySQL.AppendLine("   AND T.GIVECODE = '" + strGiveCode + "' ");
            sbQuerySQL.AppendLine("   AND T.BKGETYPE = '" + strBkgeType + "' ");
            sbQuerySQL.AppendLine("   AND T.ISSUCCESS = '1' ");
            sbQuerySQL.AppendLine("   AND T.BKGEFROM LIKE 'HYSJ%' ");
            sbQuerySQL.AppendLine("   AND UPPER(T.DBTBLNAME) = 'XYK_MEMBER_INFO' ");

            #endregion

            //clsRWFile myLog = new clsRWFile(); //将待执行的SQL语句记录下来
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", sbQuerySQL.ToString());

            double dAllAmount = 0; //上级、或上上级已经得到过的奖金总额

            clsDbSQLLogic myDB = new clsDbSQLLogic(); //实例化数据库操作类
            DataSet dsSum = myDB.YookingExecuteDataSet("Data", sbQuerySQL.ToString());
            if (dsSum != null && dsSum.Tables.Count > 0 && dsSum.Tables[0].Rows.Count > 0)
            {
                string strAllAmount = dsSum.Tables[0].Rows[0]["ALLAMOUNT"].ToString();
                if (strAllAmount == "") strAllAmount = "0"; //对空值做下数字化处理

                dAllAmount = Convert.ToDouble(strAllAmount); //奖金总额
            }

            return dAllAmount; //已经获得过的会员升级奖金总额
        }

        //注释：王庆文 2020年04月17日====================================================================================
        //填写会员佣金营收信息登记表（XYK_Income_Bill），分别将一级、二级代理、平台方佣金写入数据库
        private void saveIncomeToDB(string strUnitCode, string strReceCode, string strGiveCode,
                                     string strBkgeType, string strBkgeFrom, string strOrderID,
                                     double dBkgeAmount, string strTradeAmount,
                                     string strServiceFee, double dBkgeRate,string strDBTblName)
        {
            string strCurTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //string strUnitCode = strUnitCode;            //平台编码
            //string strReceCode = strReceCode;            //受益人编码
            //string strGiveCode = strGiveCode;            //贡献人编码
            //string strBkgeType = strBkgeType;            //佣金类型
            //string strBkgeFrom = strBkgeFrom;            //佣金来源,POS01=信用卡刷卡、POS02=信用卡还款、ATM01=信用卡套刷、ATM02=信用卡套入、HBEI01=花呗消费、HBEI02=花呗还款、BKGE01=佣金提现、HYCZ01=会员充值
            string strBkgeTime = strCurTime;               //计佣时间
            string strBkgeAmount = dBkgeAmount.ToString(); //佣金金额
            string strIsSuccess = "1";                     //是否分润成功,0=分润失败，1=分润成功
            string strATMState = "0";                      //支取状态,0=未支取，1=已支取
            string strATMTime = "";                        //支取时间
            //string strDBTblName = strDBTblName;          //资金发生库
            //string strOrderID = strOrderID;              //交易订单号
            //string strTradeAmount = strTradeAmount;      //交易总金额
            //string strServiceFee = strServiceFee;        //交易服务费
            string strBkgeRate = dBkgeRate.ToString();     //返佣比例
            string strOtherMemo = "";                      //其他备注

            var strJsonArray = "[{"; //封装成json格式的大文本数组
            strJsonArray += "\"UnitCode\":\"" + strUnitCode + "\",";       //平台编码
            strJsonArray += "\"ReceCode\":\"" + strReceCode + "\",";       //受益人编码
            strJsonArray += "\"GiveCode\":\"" + strGiveCode + "\",";       //贡献人编码
            strJsonArray += "\"BkgeType\":\"" + strBkgeType + "\",";       //佣金类型
            strJsonArray += "\"BkgeFrom\":\"" + strBkgeFrom + "\",";       //佣金来源
            strJsonArray += "\"BkgeTime\":\"" + strBkgeTime + "\",";       //计佣时间
            strJsonArray += "\"BkgeAmount\":\"" + strBkgeAmount + "\",";   //佣金金额
            strJsonArray += "\"IsSuccess\":\"" + strIsSuccess + "\",";     //是否分润成功
            strJsonArray += "\"ATMState\":\"" + strATMState + "\",";       //支取状态
            strJsonArray += "\"ATMTime\":\"" + strATMTime + "\",";         //支取时间
            strJsonArray += "\"DBTblName\":\"" + strDBTblName + "\",";     //资金发生库
            strJsonArray += "\"OrderID\":\"" + strOrderID + "\",";         //交易订单号
            strJsonArray += "\"TradeAmount\":\"" + strTradeAmount + "\","; //交易总金额
            strJsonArray += "\"ServiceFee\":\"" + strServiceFee + "\",";   //交易服务费
            strJsonArray += "\"BkgeRate\":\"" + strBkgeRate + "\",";       //返佣比例
            strJsonArray += "\"OtherMemo\":\"" + strOtherMemo + "\"";      //其他备注
            strJsonArray += "}]";

            //clsRWFile myLog = new clsRWFile(); //将请求结果保存到txt文件中
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", strJsonArray);

            DataSet dsData = clsJConvert.JArryToDataSet(strJsonArray); //将Json数组转成DataSet

            clsWriteDB myWrite = new clsWriteDB(); //先判断数据是否存在，根据判断结果自动执行insert或者update
            string strKeyColSet = "UnitCode,ReceCode,GiveCode,BkgeType,OrderID,DBTblName"; //重值判断
            myWrite.WriteDBNormal_UseSYSCol("Data", "XYK_Income_Bill", strKeyColSet, "02120119901", dsData);
        }

        #endregion


    }
}
